-- UIAwakeCarvingConfirm
-- Created by chendh
-- 觉醒雕像确认界面

-- UIAwakeCarvingConfirm继承自Layer
UIAwakeCarvingConfirm = class("UIAwakeCarvingConfirm", function()
    return cc.Layer:create();
end);

function UIAwakeCarvingConfirm.create(petId)
    return UIAwakeCarvingConfirm.new(petId);
end

-- 内部函数声明
local resize;

-- 构造函数
function UIAwakeCarvingConfirm:ctor(petId)
    -- 初始化
    self:setName("UIAwakeCarvingConfirm");
    local node = cc.CSLoader:createNode("layout/item/ItemCompound.csb");
    self:addChild(node);
    self.node = node;
    self.petId = petId;

    if DungeonM.isInDungeon() and not DungeonM.isPause() then
        -- 如果在迷宫中，需要提高层级
        self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);
    end

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 初始化窗口
    self:initForm();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 适配
    resize(node);
end

-- 适配
function resize(node)
    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 初始化窗口
function UIAwakeCarvingConfirm:initForm()
    -- 宝珠消耗
    local pearlCost = AwakeM.query(self.petId, "carving_cost");
    -- 晶核消耗
    local crystalCost = AwakeM.query(self.petId, "crystal_cost");

    -- 消耗收集完毕，记录下来
    self.pearlCost = pearlCost;
    self.crystalCost = crystalCost;

    -- 合成材料显示区域
    local costNum = #self.pearlCost + 1;
    local twoItemsNode = findChildByName(self.node, "CT/two_items");
    local threeItemsNode = findChildByName(self.node, "CT/three_items");
    local fourItemsNode = findChildByName(self.node, "CT/four_items");

    -- 根据合成材料的种类数显示不同的材料节点 目前支持2-4种
    if costNum == 2 then
        -- 消耗2种东西来合成
        twoItemsNode:setVisible(true);
        threeItemsNode:setVisible(false);
        fourItemsNode:setVisible(false);

        self.itemsNode = twoItemsNode;
    elseif costNum == 3 then
        -- 消耗3种东西来合成
        twoItemsNode:setVisible(false);
        threeItemsNode:setVisible(true);
        fourItemsNode:setVisible(false);

        self.itemsNode = threeItemsNode;
    elseif costNum == 4 then
        -- 消耗4种东西来合成
        twoItemsNode:setVisible(false);
        threeItemsNode:setVisible(false);
        fourItemsNode:setVisible(true);

        self.itemsNode = fourItemsNode;
    else
        assert(string.format("compound items num = %d.", costNum));
    end

    local itemList = {};
    for i = 1, costNum do
        local itemNode = findChildByName(self.itemsNode, "item" .. i);
        table.insert(itemList, itemNode);
    end
    self.itemList = itemList;
end

-- 重绘
function UIAwakeCarvingConfirm:redraw()
    -- 重绘物品及描述
    self:redrawItemAndDesc();

    -- 绘制公共模板背景
    self:redrawTemplate();

    -- 重绘按钮
    self:redrawButtons();

    -- 重绘标签页
    self:redrawTabs();
end

-- 绘制标签页
function UIAwakeCarvingConfirm:redrawTabs()
    local tabNode = findChildByName(self.node, "CT/tabs");
    local tabNum = 1;

    -- 先移除旧的标签
    tabNode.rows = {};
    tabNode:removeAllChildren();

    -- 根据tab数据，生成新标签
    local widget = replaceNodeWithWidget(cc.CSLoader:createNode("layout/tab/tab.csb"));

    for i = 1, tabNum do
        local child = widget:clone();
        child:setName("tab" .. i);
        child.index = i;

        self:registerTabTouchEvent(child);

        -- 计算单元格坐标
        -- 这个坐标将是单元格的描点所在
        local x = (i - 1) * 68 - 210;
        local y = -34;

        child:setPositionX(x);
        child:setPositionY(y);

        local tabLight = findChildByName(child, "light");
        local tabImage = findChildByName(child, "tab");
        tabLight:setScaleX(0.7);
        tabImage:setScaleX(0.7);

        if i == tabNum then
            tabLight:setVisible(true);
        else
            tabLight:setVisible(false);
        end

        local tabText = findChildByName(child, "text");
        local tabIcon = findChildByName(child, "icon");

        tabText:setVisible(false);
        tabIcon:loadTexture(getAwakeIconPath("carving"));
        tabIcon:setScale(0.5);

        tabNode:addChild(child)
        table.insert(tabNode.rows, child)
    end
end

-- 绘制公共模板背景
function UIAwakeCarvingConfirm:redrawTemplate()
    -- 更换公共模板上方2侧的图片
    local bgType1 = findChildByName(self.node, "CT/template/bg_type");
    local bgType2 = findChildByName(self.node, "CT/template/bg_type2");
    bgType1:loadTexture(getTitleBgIconPath("upgrade"));
    bgType2:loadTexture(getTitleBgIconPath("upgrade"));

    -- 绘制标题
    local titleLabel = findChildByName(self.node, "CT/template/title");
    local subHeadLabel = findChildByName(self.node, "CT/template/subhead");

    TextStyleM.setTitleStyle(titleLabel);
    titleLabel:setString(string.format(getLocStr("awake_carving"), PetM.query(self.petId, "short_name")));

    TextStyleM.setSubheadStyle(subHeadLabel);

    local pet = PetM.getMyPet(self.petId);
    local costTime = FormulaM.invoke("CALC_AWAKE_CARVING_COST_TIME", pet);
    subHeadLabel:setString(string.format(getLocStr("awake_carving_cost_time"), math.floor(costTime / 3600)));
end

-- 重绘道具信息
function UIAwakeCarvingConfirm:redrawItemAndDesc()
    local item = findChildByName(self.node, "CT/item");

    local buyMaterialImg = findChildByName(self.node, "CT/buy_material");
    buyMaterialImg:setVisible(false);

    -- 物品图标
    local iconImg = findChildByName(item, "item_icon");
    iconImg:loadTexture(getAwakeIconPath("carving"));

    -- 物品星级
    local starNode = findChildByName(item, "star_node");
    starNode:setVisible(false);

    -- 物品的背景框
    local frameImage = findChildByName(item, "item_bg");
    frameImage:loadTexture(getFrameBgIconPath("rank", 1));

    -- 属性描述
    local propDescLabel = findChildByName(self.node, "CT/prop_desc");
    TextStyleM.setTextStyle(propDescLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BLUE);

    local propDesc = AwakeM.fetchAwakeCarvingPropsDesc(self.petId, true);

    propStr = propDesc[1] .. "\n" .. propDesc[2];
    propDescLabel = applyString(propDescLabel, propStr);

    -- 合成消耗描述
    for i = 1, #self.itemList do
        local item = self.itemList[i];
        local itemBg = findChildByName(item, "item_bg");
        local itemIcon = findChildByName(item, "item_icon");
        local itemNum = findChildByName(item, "item_num");

        local classId;
        local ownNum = 0;
        local requireNum = 0;
        if i <= #self.pearlCost then
            classId = self.pearlCost[i][2];
            requireNum = self.pearlCost[i][3];
            ownNum = ItemM.getAmount(ME.user, classId);
        else
            classId = "crystals";
            for _, info in ipairs(self.crystalCost) do
                requireNum = requireNum + info[3];
                ownNum = ownNum + math.min(ItemM.getAmount(ME.user, info[2]), info[3]);
            end
        end

        item.index = i;
        item.classId = classId;

        if classId == "crystals" then
            -- 晶核消耗
            itemBg:setVisible(false);
            itemIcon:loadTexture(getAwakeIconPath("crystals"));
            itemIcon:setScale(1);
            TextStyleM.setTextStyle(itemNum, TextStyleM.TEXT_SIZE_TINY, TextStyleM.TEXT_COLOR_BEIGE, true, -3);

            if ownNum >= requireNum then
                applyString(itemNum, string.format("%d/%d", ownNum, requireNum), -3);
            else
                applyString(itemNum, string.format("[light_red]%d/%d[-]", ownNum, requireNum), -3);
            end
        else
            -- 物品消耗
            itemIcon:loadTexture(getItemIconPath(ItemM.query(classId, "icon")));
            itemIcon:setScale(0.8);
            TextStyleM.setTextStyle(itemNum, TextStyleM.TEXT_SIZE_TINY, TextStyleM.TEXT_COLOR_BEIGE, true, -3);

            -- 古遗迹碎片特殊处理
            local posY = itemBg:getPositionY();
            if classId == ITEM_ID_RELIC then
                itemBg:setVisible(false);
                itemIcon:setScale(1.1);
                itemIcon:setPositionY(posY + 1);
                if ownNum >= requireNum then
                    applyString(itemNum, tostring(requireNum), -3);
                else
                    applyString(itemNum, "[light_red]" .. tostring(requireNum) .. "[-]", -3);
                end
            else
                itemBg:setVisible(true);
                itemIcon:setPositionY(posY);
                if ownNum >= requireNum then
                    applyString(itemNum, tostring(ownNum) .. "/" .. tostring(requireNum), -3);
                    if ItemM.query(classId, "type") == ITEM_TYPE_MATERIAL then
                        itemIcon:setScale(0.7);
                    end
                else
                    applyString(itemNum, "[light_red]" .. tostring(ownNum) .. "[-]/" .. tostring(requireNum), -3);

                    buyMaterialImg:setVisible(true);

                    local initScale = 0.9;
                    if ItemM.query(classId, "type") == ITEM_TYPE_MATERIAL then
                        initScale = 0.7;
                    end
                    itemIcon:setScale(initScale);
                    playBubbleAnima(itemIcon, false, initScale);
                end
            end
        end

        self:registerMaterialTouchEvent(item);
    end
end

-- 重绘数量信息
function UIAwakeCarvingConfirm:redrawItemNum()
    -- 合成消耗描述
    for i = 1, #self.itemList do
        local item = self.itemList[i];

        local itemNum = findChildByName(item, "item_num");

        local classId;
        local ownNum = 0;
        local requireNum = 0;
        if i <= #self.pearlCost then
            classId = self.pearlCost[i][2];
            requireNum = self.pearlCost[i][3];
            ownNum = ItemM.getAmount(ME.user, classId);
        else
            classId = "crystals";
            for _, info in ipairs(self.crystalCost) do
                requireNum = requireNum + info[3];
                ownNum = ownNum + ItemM.getAmount(ME.user, info[2]);
            end
        end

        item.index = i;
        item.classId = classId;

        if classId == "crystals" then
            -- 晶核消耗
            if ownNum >= requireNum then
                applyString(itemNum, tostring(requireNum), -3);
            else
                applyString(itemNum, "[light_red]" .. tostring(requireNum) .. "[-]", -3);
            end
        else
            -- 物品消耗
            if ownNum >= requireNum then
                applyString(itemNum, tostring(ownNum) .. "/" .. tostring(requireNum), -3);
            else
                applyString(itemNum, "[light_red]" .. tostring(ownNum) .. "[-]/" .. tostring(requireNum), -3);
            end
        end
    end
end

-- 重绘按钮
function UIAwakeCarvingConfirm:redrawButtons()
    -- 返回按钮
    local btnBack = findChildByName(self.node, "BT/btn_back");
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 获取途径按钮
    local btnAchieve = findChildByName(self.node, "CT/btn_achieve");
    btnAchieve:setVisible(false);

    -- 合成按钮
    local buyMaterialImg = findChildByName(self.node, "CT/buy_material");
    buyMaterialImg:setVisible(false);

    -- 确定按钮
    local btnOk = findChildByName(self.node, "CT/btn_ok");
    TextStyleM.setTextStyle(btnOk, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnOk:setTitleText(getLocStr("btn_text_awake_carving"));
    btnOk:setVisible(true);

    -- 合成十个按钮
    local btnCompoundTen = findChildByName(self.node, "CT/btn_compound_ten");
    btnCompoundTen:setVisible(false);

    -- 合成按钮
    local btnCompound = findChildByName(self.node, "CT/btn_compound");
    btnCompound:setVisible(false);

    if AwakeM.canCarving(self.petId) == true and
        AwakeM.materialEnough(self.petId) == true then
        btnOk:setBright(true);
        btnOk:setTouchEnabled(true);
    else
        btnOk:setBright(false);
        btnOk:setTouchEnabled(false);
    end
end

-- 注册标签页点击回调
function UIAwakeCarvingConfirm:registerTabTouchEvent(node)
    local tabImage = node:getChildByName("tab");
    local function onClick(sender, eventType)
        -- 点击时的回调
        if eventType == ccui.TouchEventType.ended then

        end
    end

    tabImage:addTouchEventListener(onClick);
end

-- 注册材料点击回调
function UIAwakeCarvingConfirm:registerMaterialTouchEvent(node)
    local bgImage = node:getChildByName("item_bg");
    local itemImage = node:getChildByName("item_icon");
    local function onClick(sender, eventType)
        -- 点击时的回调
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");

            if node.index <= #self.pearlCost then
                -- 点击了宝珠，打开宝珠熔炼界面
                require "game/ui/form/item/UIItemCompound"
                UIMgr.getCurrentScene():removeFormByName("UIItemCompound");
                local uiForm = UIItemCompound.create(self.petId, node.classId, {"carving"});
                UIMgr.getCurrentScene():addForm(uiForm, nil, true);
            else
                -- 打开晶核界面
                require "game/ui/form/awake/UIAwakeCrystalPath"
                if UIMgr:getCurrentScene():isOpen("UIAwakeCrystalPath") then
                    UIMgr:getCurrentScene():removeForm("UIAwakeCrystalPath");
                end

                local uiForm = UIAwakeCrystalPath.create(self.petId, {"carving"});
                UIMgr.getCurrentScene():addForm(uiForm, nil, true);
            end
        end
    end

    bgImage:addTouchEventListener(onClick);
    itemImage:addTouchEventListener(onClick);
end

-- 注册点击事件
function UIAwakeCarvingConfirm:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            if self.waitCommunicate then
                -- 等待通讯不响应
                return;
            end
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UIAwakeCarvingConfirm");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);

    -- 注册确定按钮点击事件
    local btnOk = findChildByName(self.node, "CT/btn_ok");
    local function onOkClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            if self.waitCommunicate then
                -- 等待通讯不响应
                return;
            end
            AudioM.playFx("button_click");

            -- 如果冈布奥不符合条件，则弹出提示并且返回
            if AwakeM.canCarving(self.petId) ~= true then
                alert(AwakeM.canCarving(self.petId));
                return;
            end

            -- 如果材料不足够，则弹出提示并且返回
            if AwakeM.materialEnough(self.petId) ~= true then
                alert(getLocStr("awake_carving_lack_material"));
                return;
            end

            -- 开始建造雕像
            AwakeM.starCarving(self.petId);
        end
    end
    btnOk:addTouchEventListener(onOkClick);
end

-- 注册事件处理回调函数
function UIAwakeCarvingConfirm:registerEventCallback()
    -- 关注开始建造的事件
    EventMgr.register("UIAwakeCarvingConfirm", event.AWAKE_CARVING_START, function(args)
        UIMgr.getCurrentScene():removeFormByName("UIAwakeCarvingConfirm");
    end);

    -- 关注合成成功的事件
    EventMgr.register("UIAwakeCarvingConfirm", event.DO_COMPOUND, function(args)
        self:whenDoCompound(args);
    end);

    -- 注册获得焦点的回调
    EventMgr.register("UIAwakeCarvingConfirm", event.FOCUS_CHANGED, function(para)
        if para["get"] == "UIAwakeCarvingConfirm" then
            UIMgr:getCurrentScene().topMenu:show(TOPMENU_FRAME_MONEY, TOPMENU_FRAME_GEM);
        end
    end);

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            cclog("UIAwakeCarvingConfirm 界面析构清理");

            EventMgr.removeAll("UIAwakeCarvingConfirm");
        elseif ev == "enter" then

        end

    end);
end

-- 合成成功的事件
function UIAwakeCarvingConfirm:whenDoCompound(args)
    local ruleId = args.ruleId;
    local count = args.count;
    local product = CompoundM.query(ruleId, "product");

    if not product then
        -- 获取不到产物
        return;
    end

    local productInfo = product[1];

    if productInfo[1] ~= 1 then
        -- 不是物品合成
        return;
    end

    -- 重绘
    self:redraw();
end